package a66weding.com.jiehuntong.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.CommonAdapter;
import a66weding.com.jiehuntong.adapter.ViewHolder;
import a66weding.com.jiehuntong.beans.SongsBean;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.Tools;

public class LocalVideoActivity extends BaseHomeActivity implements View.OnClickListener {
    private GridView gvAllNativeVideo;
    private TextView tvTalkNoneVideo;
    private String currentUri = "";
    private String lastUri = "";
    List<SongsBean> mSongsBeans = new ArrayList<SongsBean>();
    private CommonAdapter mCommonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_video);
        initView();
       initData();
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (mCommonAdapter != null && i < 10) {
                    mCommonAdapter.notifyDataSetChanged();
                }
                if(i <= mSongsBeans.size() - 1){
                    saveBitmap2File(mSongsBeans.get(i).getMusicUri());
                }
            }else if (msg.what==1){
                if (mCommonAdapter != null) {
                    mCommonAdapter.notifyDataSetChanged();
                } else {
                    setAda();
                }
            }
        }
    };
 private  void  recurrencesFile(String  filePahts){
     File file = new File(filePahts);
        if (file.exists()){
            if (file.isDirectory()){
                recurrencesFile(file.getPath());
            }else {
                if (file.getName().endsWith(".mp4")||file.getName().endsWith(".MP4")){
                    //保存图片
                    saveBitmap2File(file.getPath());
                    //添加到文件夹
                    mSongsBeans.add(new SongsBean(file.getName(),file.getPath()));
                }
            }
        }
 }
    int i = 0;
    private void initData() {
        Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
                final String uriData = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                if (uriData.endsWith(".mp4") || uriData.endsWith(".MP4")) {
                    SongsBean songsBean = new SongsBean(title, uriData);
                    mSongsBeans.add(songsBean);
                }
            }
            cursor.close();
        }
        setAda();

        if(mSongsBeans.size() > 0){
            saveBitmap2File(mSongsBeans.get(i).getMusicUri());
        }
    }

    private void setAda() {
        if (mSongsBeans.size() > 0) {
            tvTalkNoneVideo.setVisibility(View.GONE);
            if (mCommonAdapter == null) {
                mCommonAdapter = new CommonAdapter<SongsBean>(this, mSongsBeans, R.layout.item_local_video) {
                    @Override
                    public void convert(ViewHolder holder, SongsBean songsBean) {
                        TextView tvLoacalVideo = holder.getView(R.id.tv_local_video);
                        ImageView imgSelectVideo = holder.getView(R.id.img_select_video);
                        ImageView imgLocalVideo = holder.getView(R.id.img_local_video);
                        //根据视频名称找到图片保存到了chache中了
                        Glide.with(LocalVideoActivity.this).load(FileUtil.getDefaultDir().getPath() + File.separator + songsBean.getMusicUri().substring(songsBean.getMusicUri().lastIndexOf("/") + 1, songsBean.getMusicUri().lastIndexOf(".")) + ".jpg").placeholder(R.mipmap.bg_loadimage).into(imgLocalVideo);
                        tvLoacalVideo.setText(songsBean.getMusicName());
                        if (currentUri.equals(songsBean.getMusicUri())) {
                            imgSelectVideo.setVisibility(View.VISIBLE);
                        } else {
                            imgSelectVideo.setVisibility(View.GONE);
                        }
                    }
                };
                gvAllNativeVideo.setAdapter(mCommonAdapter);
            } else {
                mCommonAdapter.notifyDataSetChanged();
            }
        } else {
            tvTalkNoneVideo.setVisibility(View.VISIBLE);
        }
    }

    private void saveBitmap2File(final String uriData) {
        //保存到了缓存文件中
        final File file = new File(FileUtil.getDefaultDir().getPath(), uriData.substring(uriData.lastIndexOf("/") + 1, uriData.lastIndexOf(".")) + ".jpg");
        if (!file.exists()) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        FileOutputStream out = new FileOutputStream(file);
                        getBitmapFromVideo(uriData).compress(Bitmap.CompressFormat.JPEG, 80, out);
                        out.flush();
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    i++;
                    mHandler.sendEmptyMessage(0);
                }
            }.start();
        }
    }

    private void initView() {
        gvAllNativeVideo = (GridView) findViewById(R.id.gv_all_native_video);
        tvTalkNoneVideo = (TextView) findViewById(R.id.tv_talk_none_video);
        //头部导航
        TextView tv_tools_dayplan_backcontent = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        LinearLayout llay_toolsheader_back = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        TextView tv_tools_dayplan_title = (TextView) findViewById(R.id.tv_tools_dayplan_title);
        TextView tv_tools_dayplan_addtype1 = (TextView) findViewById(R.id.tv_tools_dayplan_addtype1);
        ImageView img_tools_dayplan_backcontent = (ImageView) findViewById(R.id.img_tools_dayplan_backcontent);
        img_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setText("返回");
        tv_tools_dayplan_title.setText("本地视频");
        tv_tools_dayplan_addtype1.setText("");
        tv_tools_dayplan_addtype1.setVisibility(View.VISIBLE);
        llay_toolsheader_back.setOnClickListener(this);
        tv_tools_dayplan_addtype1.setOnClickListener(this);

        gvAllNativeVideo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                lastUri = currentUri;//点击在设置新的数据前保存上次点击的
                //这次点击的
                SongsBean bean = mSongsBeans.get(position);
                currentUri = bean.getMusicUri();
                int childCount = gvAllNativeVideo.getChildCount();//获得listview总共的item数量
                for (int i = 0; i < childCount; i++) {
                    //获得item的内容信息
                    SongsBean bs = (SongsBean) gvAllNativeVideo.getAdapter().getItem(i);
                    LinearLayout rootView = (LinearLayout) gvAllNativeVideo.getChildAt(i);
                    RelativeLayout childAt = (RelativeLayout) rootView.getChildAt(0);
                    ImageView imgSelect = (ImageView) childAt.getChildAt(1);
                    if (!currentUri.equals(lastUri)) {
                        if (currentUri.equals(bs.getMusicUri())) {
                            imgSelect.setVisibility(View.VISIBLE);
                        } else {
                            imgSelect.setVisibility(View.GONE);
                        }
                    } else {
                        lastUri = "";
                        currentUri = "";
                        imgSelect.setVisibility(View.GONE);
                    }
                }
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }

    public void sure_video(View view) {
        if (!currentUri.isEmpty()) {
            Intent intent = new Intent();
            intent.putExtra("videoPath", currentUri);
            setResult(999, intent);
            finish();
        } else {
            Tools.showSimpleDialog(this, "暂无选择视频,是否关闭当前页面", "否", "是", new Tools.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    finish();
                }

                @Override
                public void doCancel() {
                }
            });
        }
    }

    public void cancel_video(View view) {
        finish();
    }

    @Override
    protected void onPause() {
        Tools.dismissWaitDialog();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_toolsheader_back:
                finish();
                break;
            case R.id.img_tools_dayplan_backcontent:
                finish();
                break;
            case R.id.tv_tools_dayplan_backcontent:
                finish();
                break;
        }
    }
    private Bitmap getBitmapFromVideo(String videoFile) {
        BitmapFactory.Options bo = new BitmapFactory.Options();
        bo.inJustDecodeBounds = false;
        bo.inSampleSize = 2;
        File file = new File(videoFile);
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(file.getPath(), MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
        Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, 200, 150);
        bitmap.recycle();
        return thumbnail;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (!currentUri.isEmpty()) {
                Tools.showSimpleDialog(this, "您已选择是否放弃?", "否", "是", new Tools.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        finish();
                    }
                    @Override
                    public void doCancel() {
                        Intent intent = new Intent();
                        intent.putExtra("videoPath", currentUri);
                        setResult(999, intent);
    finish();
}
});
        return true;//当更改选项后id不一致拦截返回事件
        } else {
        finish();
        }

        }
        return super.onKeyDown(keyCode, event);
        }
        }
